/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.server;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.io.IOUtils;

import net.bioteam.appweb.Config;
import net.bioteam.appweb.gwt.apps.clientandserver.qstat.QstatProxy;
import net.bioteam.appweb.qstat.Job;
import net.bioteam.appweb.qstat.ObjectFactory;
import net.bioteam.appweb.qstat.Qstat;
import net.bioteam.appweb.qstat.Queue;
import net.bioteam.appweb.submit.UnfinishedJob;
import net.bioteam.common.user.User;
import net.bioteam.common.utils.MyEntityManager;

public class QstatImpl extends MyRemoteServiceServlet implements QstatProxy
{

	public Qstat getQstat() throws Exception
	{
		ProcessBuilder pb = new ProcessBuilder(Config.SGE_BIN_DIR+File.separator+"qstat", "-f", "-xml", "-u", "*");
		Process p = pb.start();

		InputStream in = p.getInputStream();
		p.waitFor();

		JAXBContext jc = JAXBContext.newInstance("net.bioteam.appweb.qstat");
		Unmarshaller unmarshaller = jc.createUnmarshaller();
		// unmarshaller.setListener(new myUnmarshListener());
		// unmarshaller.setEventHandler(new
		// javax.xml.bind.helpers.DefaultValidationEventHandler());
		unmarshaller.setProperty("com.sun.xml.bind.ObjectFactory", new ObjectFactory());
		Object obj = unmarshaller.unmarshal(in);
		Qstat cmd = (Qstat) obj;

		// TODO change inquiry userid

		EntityManager em = MyEntityManager.getEntityManager();
		Query query = em.createNamedQuery("allunfinishedjobs");
		List<UnfinishedJob> jobs = (List<UnfinishedJob>) query.getResultList();
		Map<String, UnfinishedJob> map = new HashMap<String, UnfinishedJob>();
		for (UnfinishedJob job : jobs)
		{
			map.put(job.getJobid(), job);
		}
		for (Job j : cmd.getPendingJobInfo().getJobs())
		{
			String jobnumber = String.valueOf(j.getJB_Job_Number());
			UnfinishedJob job = map.get(jobnumber);
			if (job != null)
			{
				String username=em.find(User.class, Long.parseLong(job.getUsername())).getName();
				j.setJB_Owner(j.getJB_Owner() + ":" + username);
			}
		}
		for (Queue q : cmd.getQueueInfo().getQueues())
		{
			for (Job j : q.getJob_List())
			{
				String jobnumber = String.valueOf(j.getJB_Job_Number());
				UnfinishedJob job = map.get(jobnumber);
				if (job != null)
				{
					String username=em.find(User.class, Long.parseLong(job.getUsername())).getName();
					j.setJB_Owner(j.getJB_Owner() + ":" + username);
				}
			}
		}

		return cmd;
	}

	
	public String getJobQstat(String jobid) throws Exception
	{
		ProcessBuilder pb = new ProcessBuilder(Config.SGE_BIN_DIR+File.separator+"qstat", "-f", "-j", jobid);
		Process p = pb.start();

		InputStream in = p.getInputStream();
		p.waitFor();

		String content=IOUtils.toString(in);
		
		p.destroy();
		return "<blockquote>"+content+"</blockquote>";
	}
	
}
